/*
 * @Description: helper 方法
 * @Author: kanglin
 * @Date: 2018-06-08 11:18:50
 * @Copyright: Created by Panxsoft.
 */

import qs from 'qs';

/**
 * 包装一个延时函数
 *
 * @param {function} callback
 * @param {int} millsecond
 */
export function delay(callback, millsecond) {
	let timer = null;
	return function delayWorker() {
		if (timer) clearTimeout(timer);
		timer = setTimeout(callback, millsecond);
	};
}


/**
 *  解析当前地区
 * @returns {string} locale
 */
export function getCurrentLocale() {
	let locale = 'zh-CN';
	const locale_value = localStorage.getItem('locale');
	if (typeof locale_value === 'string') {
		locale = locale_value;
	}
	return locale;
}

export function getBrowserLanguage() {
	const first = window.navigator.languages ? window.navigator.languages[0] : null;
	const lang = first || window.navigator.language || window.navigator.browserLanguage || window.navigator.userLanguage;
	return lang;
}


/**
 * 解析语言参数 优先选择 url search 然后是浏览器环境 (navigator.languages) 最后默认zh-CN
 * @return {string} language zh-CN OR en-US
 */
export function parseLanguageParameter() {
	const LANGUAGES = {
		'en-US': 'en-US',
		'zh-CN': 'zh-CN',
		'zh-TW': 'zh-TW',
		en: 'en-US',
		zh: 'zh-CN',
		tw: 'zh-TW',
	};
	const search = window.location.search.replace(/^\?/, '');
	const { lang } = qs.parse(search);
	const browserLanguage = getBrowserLanguage();
	return LANGUAGES[lang] || LANGUAGES[browserLanguage] || LANGUAGES['zh-CN'];
}


/**
 * 解析query string
 * @return {object} query information
 */
export function parseQueryString() {
	const query_string = window.location.search.replace(/^\?/, '');
	return qs.parse(query_string);
}

/**
 * 读取hidden属性
 * @return {String|null}
 */
export function getHiddenProp() {
	const prefixes = ['webkit', 'moz', 'ms', 'o'];
	// if 'hidden' is natively supported just return it
	if ('hidden' in document) return 'hidden';
	// otherwise loop over all the known prefixes until we find one
	for (let i = 0; i < prefixes.length; i = +1) {
		if ((`${prefixes[i]}Hidden`) in document) { return `${prefixes[i]}Hidden`; }
	}
	// otherwise it's not supported
	return null;
}

/**
 * 获取 visibilityChange 的事件在当前浏览器的时间名;
 * @return {String|null} EventName
 */
export function getVisibilityChangeEventName() {
	const hideProp = getHiddenProp();
	let eventName = null;
	if (hideProp) {
		eventName = `${hideProp.replace(/[H|h]idden/, '')}visibilitychange`;
	}
	return eventName;
}

export function getVisibilityState() {
	const prefixes = ['webkit', 'moz', 'ms', 'o'];
	if ('visibilityState' in document) return 'visibilityState';
	for (let i = 0; i < prefixes.length; i = +1) {
		if ((`${prefixes[i]}VisibilityState`) in document) { return `${prefixes[i]}VisibilityState`; }
	}
	// otherwise it's not supported
	return null;
}

/**
 *  获取当前页面hide状态
 */
export function isHidden() {
	const prop = getHiddenProp();
	if (!prop) return false;
	return document[prop];
}

